package com.example.cloud_consumer.controller;

import com.example.cloud_consumer.entity.User;
import com.example.cloud_consumer.service.HelloFeignService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: <p>
 * Company: aspire
 * </p>
 * @Author: gjj
 * @Date: 2019/8/14
 */
@RestController
public class HelloController {

    @Autowired
    private HelloFeignService helloFeignService;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    private static final Logger LOGGER = LoggerFactory.getLogger(HelloController.class);

    /*@HystrixCommand(fallbackMethod = "helloFallback",commandProperties = {
            @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value = "50000"),
            @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds",value = "10000")
    },
            threadPoolProperties = {
                    @HystrixProperty(name = "coreSize",value = "1"),
                    @HystrixProperty(name="maxQueueSize",value = "20")
            }
    )*/
    @GetMapping("/hello")
    public String hello(){
        LOGGER.info("call eureka service hello method");
        String result = helloFeignService.hello();
        return result;
    }

    @GetMapping("/helloTimeOut")
    public String helloTimeOut(){
        LOGGER.info("call eureka service helloTimeOut method");
        String result = helloFeignService.helloTimeOut();
        return result;
    }

    @PostMapping("/insertUsers")
    public void insertUsers(@RequestBody List<User> list){
        LOGGER.debug("成功进入insertUsers方法");
    }

    /**
     * 当list方法所在的服务不可用时,会调用此方法
     * @return
     */
    @Deprecated
    public String helloFallback(){
        return "fallBackHello";
    }

    /**
     * ribbon负载均衡测试方法
     */
    @GetMapping("/hello-service-instance")
    public void logUserServiceInstance(){

        ServiceInstance serviceInstance=this.loadBalancerClient.choose("hello-service");

        LOGGER.info("serviceInstance info ---> serviceId is  "+serviceInstance.getServiceId()+" host is "+serviceInstance.getHost()+"port is "+serviceInstance.getPort() );
    }
}
